package com.thunder.reader.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

import com.thunder.reader.FeedSettings;

public class UrlReader {
    private static final String TAG = FeedSettings.GLOBAL_TAG;
    private String mUrl;
    private int mConnectionTimeout;
    
    public UrlReader(String url) {
        this(url, FeedSettings.getConnectionTimeout());
    }
    
    public UrlReader(String url, int timeout) {
        mUrl = url;
        mConnectionTimeout = timeout;
    }
    
    public InputStream getInputStream() throws IOException {
        final URL url = new URL(mUrl);
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(mConnectionTimeout);
        conn.addRequestProperty(FeedSettings.PROPERTY_USER_AGENT, FeedSettings.getUserAgent());
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Log.e(TAG, "response code is not okay: " + conn.getResponseMessage());
            conn.disconnect();
            throw new IOException("response code is not okay: " + conn.getResponseCode() + ", msg " + conn.getResponseMessage());
        }
        return conn.getInputStream();
    }
    
    public String getContentAsString() throws IOException {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));
        final StringBuffer sb = new StringBuffer();
        String line = null;
        while ((line = reader.readLine())!= null) {
            sb.append(line);
        }
        reader.close();
        return sb.toString();
    }
}
